<template>
  <el-table :data="list" style="width: 100%" border stripe>
    <el-table-column label="" width="50">
      <template #default="scope">
        <el-button
          v-if="scope.$index == 0"
          :icon="Plus"
          type="success"
          circle
          @click="addRow"
          size="small"
        />
        <el-button
          v-else
          :icon="Minus"
          circle
          plain
          type="danger"
          @click="delRow(scope.$index)"
          size="small"
        />
      </template>
    </el-table-column>
    <el-table-column label="分类" width="150">
      <template #default="{ row }">
        <el-input v-model="row.cate" />
      </template>
    </el-table-column>
    <el-table-column label="金额" width="150">
      <template #default="{ row }">
        <el-input
          v-model="row.amount"
          placeholder="请输入金额"
          @input="handleInput(row)"
        />
      </template>
    </el-table-column>
    <el-table-column label="说明">
      <template #default="{ row }">
        <el-input v-model="row.remark" placeholder="请输入备注" />
      </template>
    </el-table-column>
    <el-table-column label="凭证">
      <template #default="{ row }">
        <image-upload
          :limit="1000"
          v-model="row.images"
          :item-style="itemStyle"
          :button-style="itemStyle"
        />
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
  import { ref } from 'vue';
  import { Plus, Minus } from '@element-plus/icons-vue';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  const handleInput = (row) => {
    let value = row.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    row.amount = value;
  };

  const list = ref([]);

  const addRow = () => {
    list.value.push({
      cate: '',
      amount: '',
      remark: '',
      images: ''
    });
  };
  const itemStyle = { width: '60px', height: '60px' };
  const delRow = (index) => {
    list.value.splice(index, 1);
  };
  addRow();
  defineExpose({ list }); // 让父组件可以访问 list
</script>
